package com.hang.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hang.entity.Comment;
import com.hang.entity.User;
import com.hang.exception.MyException;
import com.hang.exception.MyExceptionEnum;
import com.hang.mapper.UserMapper;
import com.hang.mapstruct.CommentMapStruct;
import com.hang.model.dto.request.CommentModelDTO;
import com.hang.model.vo.CommentInfoVO;
import com.hang.mongoEntity.CommentEntity;
import com.hang.mongoEntity.CommentImgEntity;
import com.hang.mongoEntity.DocumentEntity;
import com.hang.service.ICommentService;
import com.hang.mapper.CommentMapper;
import lombok.AllArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 *
 */
@Service
@AllArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements ICommentService{

    private MongoTemplate mongoTemplate;

    private CommentMapStruct commentMapStruct;

    private UserMapper userMapper;

    /**
     * 新增评论接口
     * @param commentModelDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createComment(CommentModelDTO commentModelDTO) {
        String content = commentModelDTO.getContent();

        Comment comment = commentMapStruct.commonModelDTOToComment(commentModelDTO);

        //先把内容缓存进mongodb中
        String mongoId = IdWorker.getIdStr();
        mongoTemplate.save(new CommentEntity(mongoId,content));

        //需要判断是否传输了图片，如果传输了图片，那么就将图片地址添加进去
        if(CollectionUtil.isNotEmpty(commentModelDTO.getImgUrlList())){
            mongoTemplate.save(new CommentImgEntity(mongoId,commentModelDTO.getImgUrlList()));
        }

        comment.setMongoId(mongoId);

        //再将内容写入数据库
        this.baseMapper.insert(comment);
    }

    /**
     * 删除评论
     * @param commentId
     * @param userId
     */
    @Override
    public void deleteComment(Long commentId, Long userId) {
        if(ObjectUtil.isNull(commentId) || ObjectUtil.isNull(userId)){
            throw new MyException(MyExceptionEnum.ID_IS_NULL);
        }

        Comment dbComment = Optional.ofNullable(this.getById(commentId)).orElse(null);

        if(ObjectUtil.isEmpty(dbComment)){
            throw new MyException(MyExceptionEnum.DATA_DOES_NOT_EXIST);
        }

        Long dbCommentUserId = dbComment.getUserId();

        //数据校验：是否是本人的评论，不是不允许删除
        if(dbCommentUserId.compareTo(userId) != 0){
            throw new MyException(MyExceptionEnum.OPERATOR_DELETE_EXCEPTION);
        }

        this.removeById(commentId);
    }

    /**
     * 获取评论展开列表
     *  1: 文档
     *  2: 任务
     *  3: 缺陷
     * @param id
     * @param type
     * @return
     */
    @Override
    public List<CommentInfoVO> getCommonListInfo(Long id, Integer type) {
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        if(type.compareTo(1) == 0) {
            //获取评论列表(评论列表展开)
            commentQueryWrapper.lambda().eq(Comment::getDocumentId, id);
        }else if(type.compareTo(2) == 0){
            commentQueryWrapper.lambda().eq(Comment::getTaskId,id);
        }else if(type.compareTo(3) == 0){
            commentQueryWrapper.lambda().eq(Comment::getBugId,id);
        }

        commentQueryWrapper.lambda().orderByDesc(Comment::getCreateTime);

        List<Comment> commentList = Optional.ofNullable(this.baseMapper.selectList(commentQueryWrapper)).orElse(new LinkedList<>());

        //评论的基础属性复制
        List<CommentInfoVO> commentInfoVOList = commentMapStruct.commentListToCommentInfoVOList(commentList);

        //内容拓展
        commentInfoVOList.forEach(
                comment -> {
                    if(StrUtil.isNotBlank(comment.getMongoId())){
                        Query query = new Query(Criteria.where("_id").is(comment.getMongoId()));
                        CommentEntity commentEntity = Optional.ofNullable(mongoTemplate.findOne(query, CommentEntity.class)).orElse(new CommentEntity());
                        if(StrUtil.isNotBlank(commentEntity.getContent())){
                            comment.setContent(commentEntity.getContent());
                        }

                        CommentImgEntity commentImgEntity = Optional.ofNullable(mongoTemplate.findOne(query,CommentImgEntity.class)).orElse(new CommentImgEntity());
                        if(CollectionUtil.isNotEmpty(commentImgEntity.getImgUrlList())){
                            comment.setImgUrlList(commentImgEntity.getImgUrlList());
                        }
                    }

                    //2023-02-24新增评论头像
                    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                    userQueryWrapper.lambda().eq(User::getUserId,comment.getUserId());
                    comment.setHeadImgUrl(Optional.ofNullable(userMapper.selectOne(userQueryWrapper).getHeadImgUrl()).orElse(""));
                }
        );

        return commentInfoVOList;
    }
}




